package com.kui.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.kui.entity.User;
import com.kui.service.UserService;
import com.kui.util.HashUtil;
import com.kui.util.UUUtil;
import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;

public class SignServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		String name = request.getParameter("signname");
		String password = request.getParameter("password");
		
		UserService us = new UserService();
		
		
		
		if(password == null){
			User u = us.findByName(name);
			if(u != null){
				out.print("fail");
			}else{
				out.print("ok");
			}
		}else{
			String jcaptcha = request.getParameter("checkcode");
			if(jcaptcha == null || "".equals(jcaptcha)){
				out.print("checkerror");
				return;
			}
			jcaptcha = jcaptcha.toLowerCase();
			boolean result = SimpleImageCaptchaServlet.validateResponse(request, jcaptcha);
			if(!result){
				out.print("checkerror");
				return;
			}
			User u = us.findByName(name);
			if(u != null){
				out.print("fail");
				return;
			}
			
			try {
				password=HashUtil.getHashString(password);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(password);
			 u = new User();
			u.setId(UUUtil.getUUID());
			u.setPassword(password);
			u.setUsername(name);
			
			us.sign(u);
			out.print("ok");
		}
		
		out.flush();
		out.close();
	}
	
	
}
